/**
 * 
 */
package com.es.disped.web.controller.permission;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.es.disped.api.permission.PermissionService;
import com.es.disped.api.rolepermission.RolePermissionService;
import com.es.disped.common.constant.RecordStatus;
import com.es.disped.common.model.MsgModel;
import com.es.disped.core.annotation.LogInject;
import com.es.disped.core.controller.BaseController;
import com.es.disped.dao.model.Permission;
import com.es.disped.dao.model.PermissionExample;
import com.es.disped.dao.model.PermissionNode;
import com.es.disped.dao.model.PermissionType;
import com.es.disped.dao.model.RolePermissionRelExample;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * @author Anson<br>
 *
 * Copyright by EasyShare 2019<br>
 *
 * All right reserved<br>
 *
 * Created on 下午4:31:39<br>
 *
 * 名称：PermissionController.java<br>
 *
 * 描述：权限管理<br>
 */
@Api(value="权限管理")
@Controller
@RequestMapping("/manage/permission")
public class PermissionController extends BaseController{
	
	private static final String NAMESPACE="com.es.disped.dao.mapper.permission.PermissionCustomMapper";

	@LogInject
	Logger log;
	
	@Autowired
	PermissionService permissionService;
	@Autowired
	RolePermissionService rolePermissionService;
	
	@ApiOperation(value="权限保存",response=MsgModel.class,httpMethod="POST",notes="保存新权限-管理端")
	@RequiresPermissions(value= {"admin:save","sys:save"},logical=Logical.OR)
	@RequestMapping(value="/save",method=RequestMethod.POST)
	@Transactional
	public @ResponseBody MsgModel save(@RequestBody @ApiParam(name="permission",value="权限对象",required=true) Permission permission)
	{
		int count=0;
		if(Optional.of(permission)
				.filter(name->permission.getPermissionName()!=null)
				.filter(parentId->permission.getPermissionParentId()!=null)
				.filter(code->permission.getPermissionCode()!=null)
				.isPresent())
		{
			permission.setPermissionId(getUUID());
			permission.setPermissionType(PermissionType.PERMISSION.getValue());
			permission.setPermissionValid(RecordStatus.USEAGE.getValue());
			count=permissionService.insertSelective(permission);
			Permission oldParentNode=permissionService.selectByPrimaryKey(permission.getPermissionParentId());
			//修改父节点类型
			if(PermissionType.PERMISSION.getValue().equals(oldParentNode.getPermissionType()))
			{
				Permission parentNode=new Permission();
				parentNode.setPermissionType(PermissionType.GROUP.getValue());
				PermissionExample permissionExample=new PermissionExample();
				permissionExample.createCriteria().andPermissionIdEqualTo(oldParentNode.getPermissionId());
				permissionService.updateByExampleSelective(parentNode, permissionExample);
			}
		}
		log.debug(count==1?HttpStatus.OK.value()+"-权限保存成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-权限保存失败",permission);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"权限保存成功":"权限保存失败", permission);
	}
	
	@ApiOperation(value="权限更新",response=MsgModel.class,httpMethod="POST",notes="更新权限-管理端")
	@RequiresPermissions(value= {"admin:update","sys:update"},logical=Logical.OR)
	@RequestMapping(value="/update",method=RequestMethod.POST)
	public @ResponseBody MsgModel update(@RequestBody @ApiParam(name="permission",value="权限对象",required=true) Permission permission)
	{
		int count=0;
		if(Optional.of(permission)
				.filter(id->permission.getPermissionId()!=null)
				.isPresent())
		{
			count=permissionService.updateByPrimaryKeySelective(permission);
		}
		log.debug(count==1?HttpStatus.OK.value()+"-权限更新成功":
			HttpStatus.EXPECTATION_FAILED.value()+"-权限更新失败",permission);
		return new MsgModel(count==1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				count==1?"权限更新成功":"权限更新失败", permission);
	}
	
	@ApiOperation(value="删除权限",response=MsgModel.class,httpMethod="POST",notes="根据权限主键删除权限-管理端")
	@RequiresPermissions(value= {"admin:delete","sys:delete"},logical=Logical.OR)
	@Transactional
	@RequestMapping(value="/delete",method=RequestMethod.POST)
	public @ResponseBody MsgModel delete(@RequestBody @ApiParam(name="permission",value="权限对象",required=true) Permission permission)
	{
		int pCount=0,relCount=0;
		if(Optional.of(permission)
				.filter(pId->permission.getPermissionId()!=null)
				.filter(ppId->permission.getPermissionParentId()!=null)
				.isPresent())
		{
			//删除权限引用
			RolePermissionRelExample rolePermissionRelExample=new RolePermissionRelExample();
			rolePermissionRelExample.createCriteria().andPermissionIdEqualTo(permission.getPermissionId());
			relCount=rolePermissionService.deleteByExample(rolePermissionRelExample);
			//删除权限节点及子节点
			PermissionExample permissionExample=new PermissionExample();
			permissionExample.createCriteria().andPermissionParentIdEqualTo(permission.getPermissionId());
			pCount+=permissionService.deleteByExample(permissionExample);//删除子节点
			pCount+=permissionService.deleteByPrimaryKey(permission.getPermissionId());//删除当前节点
			//修改权限父类节点
			PermissionExample parentExample=new PermissionExample();
			parentExample.createCriteria().andPermissionParentIdEqualTo(permission.getPermissionParentId());
			List<Permission> list=permissionService.selectByExample(parentExample);
			if(this.isNull(list))
			{
				Permission parentNode=new Permission();
				parentNode.setPermissionType(PermissionType.PERMISSION.getValue());
				PermissionExample parentPermissionExample=new PermissionExample();
				parentPermissionExample.createCriteria().andPermissionIdEqualTo(permission.getPermissionParentId());
				permissionService.updateByExampleSelective(parentNode, parentPermissionExample);
			}
		}
		log.debug(pCount>=1?HttpStatus.OK.value()+"-权限删除成功，共删除"+pCount+"个权限，"+relCount+"个引用":
			HttpStatus.EXPECTATION_FAILED.value()+"-权限删除失败，共删除"+pCount+"个权限，"+relCount+"个引用");
		return new MsgModel(pCount>=1?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				pCount>=1?"权限删除成功，共删除"+pCount+"个权限，"+relCount+"个引用":"权限删除失败");
	}
	
	@ApiOperation(value="权限检索",response=MsgModel.class,httpMethod="POST",notes="根据权限可检索字段检索权限列表-管理端")
	@RequestMapping(value="/list",method=RequestMethod.POST)
	public @ResponseBody MsgModel list(@RequestBody @ApiParam(name="permission",value="权限对象",required=false) Permission permission)
	{
		PermissionExample example=new PermissionExample();
		if(!this.isNull(permission.getPermissionName()))
		{
			example.createCriteria().andPermissionNameLike("%"+permission.getPermissionName()+"%");
		}
		if(!this.isNull(permission.getPermissionId()))
		{
			example.createCriteria().andPermissionIdEqualTo(permission.getPermissionId());
		}
		List<Permission> permissions=permissionService.selectByExample(example);
		return new MsgModel(permissions.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
				permissions.size()>0?"":"权限列表为空", permissions.size()>0?permissions:"");
	}
	
//	@ApiOperation(value="权限列表分页查询",response=MsgModel.class,httpMethod="POST",notes="分页加载权限列表-管理端")
//	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
//	@RequestMapping(value="/pages",method=RequestMethod.POST)
//	public @ResponseBody MsgModel pages(@RequestBody @ApiParam(name="paramMap",value="分页参数[offset,limit]",required=true) Map<String, Object> paramMap)
//	{
//		PermissionExample example=new PermissionExample();
//		PageModel<Permission> pageModel=null;
//		if(Optional.of(paramMap)
//				.filter(offset->paramMap.containsKey("offset")!=false)
//				.filter(limit->paramMap.containsKey("limit")!=false)
//				.isPresent())
//		{
//			pageModel=permissionService.selectByExampleForOffsetPage(example,
//					Integer.valueOf(paramMap.get("offset").toString()), Integer.valueOf(paramMap.get("limit").toString()));
//		}
//		return new MsgModel(pageModel!=null?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
//				pageModel!=null?"":"权限加载失败", pageModel!=null?pageModel:"");
//	}
	
	
	@ApiOperation(value="获取权限Tree结构列表",response=MsgModel.class,httpMethod="POST",notes="根据权限ID检索权限Tree列表-管理端")
	@RequiresPermissions(value= {"admin:select","sys:select"},logical=Logical.OR)
	@RequestMapping(value="/permissionTree",method=RequestMethod.POST)
	public @ResponseBody MsgModel getPermissionTree(@RequestBody @ApiParam(name="paramMap",value="当前检索的Tree的起始节点ID，若默认为空则从根节点开始",required=false) Map<String, Object> paramMap)
	{
		if (!paramMap.containsKey("id")) {
            paramMap.put("id", "00000000000000000000000000000000");
        }
		List<PermissionNode> nodeList=new ArrayList<>();
		List<PermissionNode> rootList=this.getService().selectList(NAMESPACE+".getPermissionNode", paramMap.get("id"));
		for(PermissionNode permissionNode:rootList)
		{
			permissionNode.setChildren(getPermissionNode(permissionNode.getId()));
			nodeList.add(permissionNode);
		}
        return new MsgModel(nodeList.size()>0?HttpStatus.OK.value():HttpStatus.EXPECTATION_FAILED.value(),
        		nodeList.size()>0?"":"列表加载失败", nodeList.size()>0?nodeList:"");
	}

	/**
	 * 获取Tree结构权限集合
	 * @param pid
	 * 		{@link String} pid	权限父类ID
	 * @return
	 * 		List<PermissionNode>	权限节点列表集合
	 */
	private List<PermissionNode> getPermissionNode(String pid) {
		List<PermissionNode> permissionList=this.getService().selectList(NAMESPACE+".getPermissionNode", pid);
		return permissionList;
	}
}
